//
//  is.cpp
//  
//
//  Created by Nikita Luzyanin on 30.11.13.
//
//

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
#include "functions.cpp"
using namespace std;

#define DATE_PARTS 5

int main(int argc, char* argv[])
{
    char pathToRoot[1000], pathInFS[1000];
    char *pathToFS;
    
    pathToFS = argv[1];
    if (argv[2]) {
        strcpy(pathInFS, argv[2]);
    } else {
        strcpy(pathInFS, "/0");
    }
    FILE *f;
    f = fopen(pathToFS, "rb");
    if (f == NULL) {
        cout << "Path to FS does not exist\n";
        return 1;
    }
    fclose(f);
    
    strcpy(pathToRoot, pathToFS);
    strcat(pathToRoot, "/0");
    f = fopen(pathToRoot, "rb");
    if (f == NULL) {
        cout << "FS is not formatted\n";
        return 1;
    }
    fclose(f);
    
    char metaBlock[10];
    if (findMetaBlock(pathToFS, metaBlock, pathInFS, false, false, false) != 0) {
        cout << "File does not exist\n";
        return 1;
    }
    
    fstream F;
    int type, size;
    char name[12], date[20], dateHelper[20], pathToContentBlock[1000], pathToMetaBlock[1000], contentBlock[10], contentName[10], ch, temp[1000], parentMetaBlock[10];
    if (pathInFS == NULL) {
        strcpy(pathInFS, "/0");
    }
    
    strcpy(pathToMetaBlock, pathToFS);
    strcat(pathToMetaBlock, metaBlock);
    F.open(pathToMetaBlock);
    F >> name;
    ch = name[strlen(name)-1];
    cout << "NAME : " << name << "\n";
    F >> contentBlock;
    F >> parentMetaBlock;
    F >> size;
    cout << "SIZE : " << size << "\n";
    
    F >> date;
    for (int i = 0; i < DATE_PARTS - 1; i++) {
        F >> dateHelper;
        strcat(date, " ");
        strcat(date, dateHelper);
    }
    
    cout << "DATE MODIFIED : " << date << "\n";
    F.close();
    
    strcpy(pathToContentBlock, pathToFS);
    strcat(pathToContentBlock, contentBlock);
    F.open(pathToContentBlock);
    if (ch == '/') {
        // F >> temp;
        F >> contentBlock;
        cout << "CONTENTS :\n";
        ch = F.get();
        ch = F.peek();
        while (ch == '/') {
            ch = F.get();
            F >> contentName;
            F >> temp;
            cout << contentName << "\n";
            ch = F.get();
            ch = F.peek();
            // skips eol and '/' to next content
        }
    } else {
        
    }
    F.close();
    
    return 0;
}